var LuckyDrawOptions = {
	segments: {},
	colors: '',
	url: ''
};
(function() {
	$(function() {
		var playFlag = 'try',
				index,
				playing = false;
		$('#luckydraw').luckydraw({
			segments: LuckyDrawOptions.segments,
			colors: LuckyDrawOptions.colors,
			fps: 33,
			onfinish: function(e) {
				playing = false;
				if (playFlag == 'play') {
					var $result = $('#luckydraw-result');
					$result.fadeIn(2000);
					$('html, body').animate({scrollTop: $result.offset().top}, 1000);
					$('#luckydraw-winning').html(LuckyDrawOptions.segments[index - 1].text);
					$('.luckydraw-trigger').hide();
				} else {
					$('#luckydraw-play').fadeIn(1000);
					$('#luckydraw-try').html($('#luckydraw-try').data('_html'));
				}
				$('.luckydraw-reward li').eq(index - 1).append('<span class="selected icon-star-empty" />');
			}
		});
		$('#luckydraw-play').click(function() {
			playFlag = 'play';
			$('#luckydraw-try').remove();
		});
		$('.luckydraw-trigger').click(function() {
			if (playing) {
				return;
			}
			playing = true;
			$('.luckydraw-reward .selected').remove();

			var $element = $(this);
			$element.data('_html', $element.html());
			$element.html('Playing ...');
			if (playFlag == 'play') {
				$element.off();
			} else {
				$('#luckydraw-play').stop().fadeOut();
			}
			$.ajax({
				url: LuckyDrawOptions.url,
				method: "get",
				dataType: 'json',
				data: {
					flag: playFlag
				},
				cache: false,
				success: function(data) {
					try {
						if (data != undefined && data._index > 0) {
							index = data._index;
							$('#luckydraw').data('luckydraw').play(data._index);
						} else {
							alert("Error");
							location.reload();
						}
					} catch (e) {
						alert('Can not connect to server');
					}
				}
			});
		});
	});

})(jQuery);